import { HttpContext } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { ALLOW_ANONYMOUS } from '@delon/auth';
import {SFSchema, SFSelectWidgetSchema, SFTreeSelectWidgetSchema, SFUISchema} from '@delon/form';
import { _HttpClient } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { Api } from 'src/app/shared/api/api';
import { SIX, USER_LABEL_ENUM, VCATEGORIES, XS_SERVICE, XS_SOURCE } from 'src/app/shared/constant/common-constant';
import { ResponseCode } from 'src/app/shared/response.code';

@Component({
  selector: 'app-system-user-edit',
  templateUrl: './user-edit.component.html'
})
export class UserEditComponent implements OnInit {
  record: any = {};
  status: any;
  readonly: boolean = false;
  userLabel: any = [];
  userStatus: any = [];
  xs_source_list: any = [];
  xs_service_list: any = [];
  six_list: any = [];
  schema: SFSchema = { properties: {} };
  ui: SFUISchema = {
    '*': {
      spanLabel: 10,
      spanControl: 14,
      grid: { span: 12 }
    }
  };

  constructor(private modal: NzModalRef, private msgSrv: NzMessageService, public http: _HttpClient) {}

  ngOnInit(): void {
    this.readonly = this.record.id && this.record.id.length > 0;
    this.userLabel = USER_LABEL_ENUM.filter(item => item.value.length > 0);
    this.userStatus = VCATEGORIES.filter(item => item.value !== null);
    this.xs_source_list = XS_SOURCE.filter(item => item.value !== null);
    this.xs_service_list = XS_SERVICE.filter(item => item.key !== null);
    this.six_list = SIX.filter(item => item.value !== null);
    this.initSchema();
  }

  // 初始化表单，在获取完部门树数据之后再初始化
  initSchema() {
    this.schema = {
      properties: {
        name: {
          type: 'string',
          title: '法人',
          readOnly: this.readonly
        },
        company_name: {
          type: 'string',
          title: '公司名称'
        },
        company_address: {
          type: 'string',
          title: '公司地址'
        },
        phone: {
          type: 'string',
          title: '电话号码',
          pattern: '^1\\d{10}$',
          readOnly: this.readonly
        },
        business_scope: {
          type: 'string',
          title: '经营范围',
          readOnly: this.readonly
        },
        business_style: {
          type: 'string',
          title: '项目服务种类',
          readOnly: this.readonly,
          enum: this.xs_service_list,
          default: ['注册执照（个体）'],
          ui: {
            widget: 'tree-select',
            multiple: true,
          } as SFTreeSelectWidgetSchema
        },
        company_num: {
          type: 'string',
          title: '企业规模',
          readOnly: this.readonly
        },
        company_creat_time: {
          type: 'string',
          title: '成立日期',
          readOnly: this.readonly,
          ui: {
            widget: 'date'
          }
        },
        gk_company_name: {
          type: 'string',
          title: '挂靠公司名称',
          readOnly: this.readonly
        },
        gk_company_region: {
          type: 'string',
          title: '挂靠公司区域',
          readOnly: this.readonly
        },
        gk_company_creat_time: {
          type: 'string',
          title: '挂靠成立日期',
          readOnly: this.readonly,
          ui: {
            widget: 'date'
          }
        },
        company_money: {
          type: 'string',
          title: '注册资本',
          readOnly: this.readonly
        },
        company_code: {
          type: 'string',
          title: '统一社会信用代码',
          readOnly: this.readonly
        },
        six: {
          type: 'string',
          title: '性别',
          enum: this.six_list,
          default: '男',
          ui: {
            widget: 'select'
          } as SFSelectWidgetSchema
        },
        wxchat: {
          type: 'string',
          title: '微信号',
          readOnly: this.readonly
        },
        industry: {
          type: 'string',
          title: '行业',
          enum: this.userStatus,
          default: '农林牧渔',
          ui: {
            widget: 'select'
          } as SFSelectWidgetSchema
        },
        xs_source: {
          type: 'string',
          title: '线索来源',
          enum: this.xs_source_list,
          default: '广告',
          ui: {
            widget: 'select'
          } as SFSelectWidgetSchema
        }
      },
      required: ['name', 'phone', 'company_name', 'company_address']
    };
  }

  save(value: any) {
    console.log(value);
    value.status = this.status;
    value.business_style = value.business_style.toString();
    value.customer_status = '正常';
    if (this.record.id) {
      this.http
        .post(Api.BaseCustomerUpdateApi, value, {}, { context: new HttpContext().set(ALLOW_ANONYMOUS, true) })
        .subscribe((res: any) => {
          if (res) {
            if (res.code === ResponseCode.SUCCESS) {
              this.msgSrv.success('修改成功');
              this.modal.close(true);
            } else {
              this.msgSrv.warning(res.message);
            }
          } else {
            this.msgSrv.error('修改失败，未知错误');
          }
        });
    } else {
      this.add(value);
    }
  }
  add(value: any) {
    value.last_flow_up_name = localStorage.getItem('user_name');
    this.http
      .post(
        Api.BaseAddCustomerApi,
        [value],
        {},
        {
          headers: {
            Authorization: 'Bearer dGVzdDp0ZXN0'
          },
          context: new HttpContext().set(ALLOW_ANONYMOUS, true)
        }
      )
      .subscribe((res: any) => {
        if (res && res.code === ResponseCode.SUCCESS) {
          this.msgSrv.success('保存成功');
          if (res.data && res.data.length > 0) {
            for (let i in res.data) {
              this.msgSrv.success(`该客户： ${res.data[i].name} 已被 ${res.data[i].last_flow_up_name} 跟进`);
            }
          }
          this.modal.close(true);
        }
      });
  }
  close() {
    this.modal.destroy();
  }
}
